﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Threading;

namespace MyUtils.UI
{
	public class DispatchableObservable : INotifyPropertyChanged
	{
		private readonly Dispatcher _dispatcher;

		public DispatchableObservable()
		{
			_dispatcher = DefaultDispatcher;
		}

		public static Dispatcher DefaultDispatcher
		{
			get
			{
				var app = Application.Current;
				if (app != null)
				{
					return app.Dispatcher;
				}
				return null;
			}	
		}

		public static void DefaultDispatcherInvoke(Action<object> act, object state = null)
		{
			if (act != null)
			{
				var disp = DefaultDispatcher;
				if (disp != null)
				{
					disp.BeginInvoke(act, state);
				}
			}
		}

		public DispatchableObservable(Dispatcher dispatcher)
		{
			_dispatcher = dispatcher;
		}

		public event PropertyChangedEventHandler PropertyChanged;

		public void OnPropertyChanged(string name)
		{
			var handler = PropertyChanged;
			if (handler != null)
			{
				var args = new PropertyChangedEventArgs(name);
				if (_dispatcher == null || _dispatcher == Dispatcher.CurrentDispatcher)
				{
					handler(this, args);
				}
				else
				{
					_dispatcher.BeginInvoke(new Action(() => handler(this, args)));
				}
			}
		}


	}
}
